<template>
  <q-dialog v-model="isShow" persistent>
    <q-card>
      <q-card-section class="row items-center q-pb-none">
        <!-- dialog框标题 -->
        <div class="text-h6">管理作业动作</div>
        <q-space />
        <q-btn
          color="primary"
          label="新增动作"
          icon="playlist_add"
          style="margin: 0 20px 0 50px"
          @click="addActionClick"
        />
        <q-btn
          icon="close"
          flat
          round
          dense
          v-close-popup
          @click="closeActionListDialog"
        />
      </q-card-section>

      <q-separator style="margin-top: 12px" />

      <q-table
        class="sticky-header-table no-border-radius"
        style="min-height: 10rem; max-height: calc(100vh - 10rem)"
        :rows="actions"
        :columns="columns"
        virtual-scroll
        :rows-per-page-options="[0]"
        :virtual-scroll-sticky-size-start="48"
        hide-bottom
        row-key="id"
      >
        <!--列名插槽-->
        <template v-slot:header="props">
          <q-tr :props="props" class="my-header">
            <q-th v-for="col in props.cols" :key="col.name" :props="props">
              {{ col.label }}
            </q-th>
          </q-tr>
        </template>

        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td v-bind:key="'priority'" :props="props">
              {{ props.row.datas[0].value }}
            </q-td>
            <q-td v-bind:key="'device'" :props="props">
              {{ props.row.datas[1].value }}
            </q-td>
            <q-td v-bind:key="'actionType'" :props="props">
              {{
                props.row.datas[2].options.find((value) => {
                  return value.value === props.row.datas[2].value;
                }).label
              }}
            </q-td>
            <q-td v-bind:key="'modify'" :props="props">
              <q-btn
                align="around"
                size="sm"
                color="primary"
                label="修改"
                icon="edit"
                @click="modifyPlanActionClick(props.rowIndex)"
              />
            </q-td>
            <q-td v-bind:key="'delete'" :props="props">
              <q-btn
                align="around"
                size="sm"
                color="red-10"
                label="删除"
                icon="delete"
                @click="deletePlanAction(props.rowIndex)"
              />
            </q-td>
          </q-tr>
        </template>
      </q-table>

      <div class="flex">
        <q-input
          outlined
          v-model="executeCount"
          label="执行次数"
          style="width: 100px"
          type="number"
          dense
        />
        <q-btn
          color="accent"
          :label="executeLabel"
          icon="check"
          style="flex: 1"
        />
      </div>
    </q-card>
  </q-dialog>

  <input-dialog
    :title="isModifyActionDialog ? '修改动作' : '增加动作'"
    :fields="
      isModifyActionDialog ? modifyActinDialogFields : actionDialogFields
    "
    :dialog-show-value="isShowActionDialog"
    @close="closeActionDialog"
    @onConfirm="confirmAddPlanAction"
  ></input-dialog>
</template>

<script setup>
import { computed, ref, toRaw, watch } from "vue";
import InputDialog from "components/dialog/InputDialog.vue";
import { useDataStore } from "stores/data";
import { api } from "boot/axios";
import { useAPIStore } from "stores/api";

const columns = [
  {
    name: "priority",
    label: "优先度",
    field: "priority",
    align: "center",
  },
  {
    name: "device",
    label: "执行设备",
    field: "device",
    align: "left",
  },
  {
    name: "actionType",
    label: "动作类型",
    field: "type",
    align: "center",
  },
  {
    name: "modify",
    label: "修改动作",
    field: "modify",
    align: "center",
  },
  {
    name: "delete",
    label: "删除动作",
    field: "delete",
    align: "center",
  },
];
const modifyActinDialogFields = ref([
  {
    key: "priority",
    name: "优先度",
    value: "",
    type: "number",
  },
  {
    key: "device",
    name: "目标设备",
    value: "",
  },
  {
    key: "actionType",
    name: "动作类型",
    value: "",
    type: "select",
  },
]);
const actionDialogFields = ref([
  {
    key: "priority",
    name: "优先度",
    value: "",
    type: "number",
  },
  {
    key: "device",
    name: "目标设备",
    value: "",
  },
  {
    key: "actionType",
    name: "动作类型",
    value: "",
    type: "select",
  },
]);

const devices = ref([]);

const actionTypes = JSON.parse(JSON.stringify(useDataStore().actionList));
console.log("111111", actionTypes);
console.log(
  "0000000",
  actionTypes.map((actions) => {
    return {
      label: actions[1].value,
      value: actions[0].value,
    };
  })
);
// 初始化动作类型
actionDialogFields.value[2].options = actionTypes.map((actions) => {
  return {
    label: actions[1].value,
    value: actions[0].value,
  };
});
const bottomFieldsCount = ref(0);
// 监听动作类型变化
watch(actionDialogFields.value[2], () => {
  console.log("监听到变化", actionDialogFields);
  const rawActionTypes = toRaw(actionTypes);
  // console.log('actionTypes', rawActionTypes)
  const newActionsTypes = rawActionTypes.filter((actions, index) => {
    if (actionDialogFields.value[2].value === actions[0].value) {
      return true;
    }
    return false;
  });

  // 取到动作路径，动作名称后的字段
  if (newActionsTypes.length > 0) {
    const currentAction = newActionsTypes[0];
    if (currentAction.length > 2) {
      currentAction.splice(0, 2);
    }
    for (let i = 0; i < bottomFieldsCount.value; i++) {
      actionDialogFields.value.pop();
    }
    // 遍历添加后面的字段
    currentAction.forEach((field) => {
      // TODO 这里会造成在修改动作类型的时候把另外的类型累加进来
      actionDialogFields.value.push({
        key: field.key,
        name: field.value,
        value: "",
      });
    });
    bottomFieldsCount.value = currentAction.length;
  }
});

const executeCount = ref(1);
const executeLabel = computed(() => {
  return `执行${executeCount.value}次`;
});
const isShowActionDialog = ref(false);
const isModifyActionDialog = ref(false);
const actions = computed(() => {
  const newActions = useDataStore().planActions.filter((action) => {
    if (action.key === planId.value) {
      return true;
    } else {
      return false;
    }
  });
  return newActions;
});
const planId = ref("");
const isShow = ref(false);

function closeActionListDialog() {
  isShow.value = false;
}

function showActionListDialog(device, id) {
  planId.value = id;
  if (device === null) {
    getDevices();
    actionDialogFields.value[1].disable = false;
    actionDialogFields.value[1].value = "";
  } else {
    actionDialogFields.value[1].type = "text";
    actionDialogFields.value[1].disable = true;
    actionDialogFields.value[1].value = device;
  }
  isShow.value = true;
}

/**
 * 获取所有设备数据
 */
function getDevices() {
  api.get(useAPIStore().centerUrl + "configs/all").then((rs) => {
    devices.value = rs.data.map((item) => {
      return item.id;
    });
    actionDialogFields.value[1].type = "select";
    actionDialogFields.value[1].options = devices.value;
  });
}

/**
 * 增加动作按钮点击，弹出添加动作弹框
 */
function addActionClick() {
  isShowActionDialog.value = true;
  isModifyActionDialog.value = false;
}

/**
 * 关闭添加动作弹框
 */
function closeActionDialog() {
  isShowActionDialog.value = false;
}

/**
 * 增加动作
 */
function confirmAddPlanAction() {
  const obj = {};
  if (isModifyActionDialog.value) {
    // 修改动作
    obj.key = planId.value;
    obj.datas = modifyActinDialogFields.value;
    useDataStore().planActions.splice(modifyPlanActionIndex.value, 1, obj);
  } else {
    // 增加动作
    obj.key = planId.value;
    obj.datas = actionDialogFields.value;
    useDataStore().planActions.push(obj);
  }
  isShowActionDialog.value = false;
}

/**
 * 删除作业动作
 */
function deletePlanAction(index) {
  const planActionsIndex = useDataStore().planActions.findIndex(
    (planAction) => {
      return (
        planAction.key === planId.value &&
        planAction.datas[0].value === actions.value[index].datas[0].value
      );
    }
  );
  useDataStore().planActions.splice(planActionsIndex, 1);
}

const modifyPlanActionIndex = ref(-1);

/**
 * 修改作业动作
 * @param index
 */
function modifyPlanActionClick(index) {
  isShowActionDialog.value = true;
  isModifyActionDialog.value = true;
  const planAction = useDataStore().planActions.find((planAction) => {
    return (
      planAction.key === planId.value &&
      planAction.datas[0].value === actions.value[index].datas[0].value
    );
  });
  modifyPlanActionIndex.value = useDataStore().planActions.findIndex(
    (planAction) => {
      return (
        planAction.key === planId.value &&
        planAction.datas[0].value === actions.value[index].datas[0].value
      );
    }
  );
  modifyActinDialogFields.value = JSON.parse(JSON.stringify(planAction.datas));
}

defineExpose({
  showActionListDialog,
});
</script>

<style lang="scss" scoped>
.my-header th {
  color: black;
  font-weight: bold;
  font-size: 13px;
  position: sticky;
  z-index: 1;
  background: white;
}

.my-header:first-child th {
  top: 0;
}
</style>
